﻿using MesBSW.DAL.MesDB;
using MesBSW.View;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MesBSW.BLL.Mes
{
    public class ExcepOrderControler : BaseControler
    {
        /// <summary>
        /// 根据工单号查询工单信息
        /// </summary>
        /// <param name="prodNo"></param>
        /// <returns></returns>
        public TargetProdProcess SearchTargetProdProcessForProdNo(string prodNo)
        {
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.TargetProdProcesses.Where(p => p.ProdNumber == prodNo);
                if (query != null && query.Count() > 0)
                {
                    return query.First<TargetProdProcess>();
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 根据服务器的日期取得当天最大的维修单单号
        /// </summary>
        /// <returns></returns>
        public string GetMaxRepairNumber()
        {
            string repNumber = "";
            DateTime tmpDay = this.GetCurrDateTime();
            repNumber = "REP" + tmpDay.ToString("yyyy") + tmpDay.ToString("MM") + tmpDay.ToString("dd");
            using (MesDB ctx = new MesDB())
            {
                var maxQuery = ctx.ExcepOrder.Where(o => o.RepairNumber.Contains(repNumber)).OrderByDescending(o => o.RepairNumber);

                if (maxQuery != null && maxQuery.Count() > 0)
                {
                    int tmpIndex = int.Parse(maxQuery.First<ExcepOrder>().RepairNumber.Substring(11, 5));
                    repNumber = repNumber + (tmpIndex + 1).ToString().PadLeft(5, '0');
                }
                else
                {
                    repNumber = repNumber + "00001";
                }
            }
            return repNumber;
        }

        /// <summary>
        /// 新增维修单
        /// </summary>
        /// <param name="orderBean"></param>
        /// <param name="picBean"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int InsertExcepOrder(ExcepOrder orderBean, ExcepPicture picBean)
        {
            int count = 0;
            DateTime tmpDay = this.GetCurrDateTime();
            using (MesDB ctx = new MesDB())
            {
                string prodNo = orderBean.ProdNumber;
                var query = ctx.TargetProdProcesses.Where(p => p.ProdNumber == prodNo);
                if (query != null && query.Count() > 0)
                {
                    TargetProdProcess tarBean = query.First<TargetProdProcess>();
                    using (var tran = ctx.Database.BeginTransaction())
                    {
                        try
                        {
                            orderBean.TargetID = tarBean.ID;
                            orderBean.CreateDate = tmpDay;
                            orderBean.CreateUser = MainFrm.LoginUser.user_name;

                            ctx.ExcepOrder.Add(orderBean);
                            count = count + ctx.SaveChanges();

                            picBean.TargetID = tarBean.ID;
                            picBean.RepairID = orderBean.ID;
                            ctx.ExcepPicture.Add(picBean);
                            count = count + ctx.SaveChanges();

                            tarBean.ErrStatusID = orderBean.ErrStatusID;
                            count = count + ctx.SaveChanges();

                            tran.Commit();
                            return count;
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            throw ex;
                        }
                    }
                }
                else
                {
                    throw new Exception("系统中无法找到工单");
                }
            }
        }


        /// <summary>
        /// 根据条件查询维修记录
        /// </summary>
        /// <param name="repBean">载有查询条件的Bean</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageCount">每页显示记录数</param>
        /// <returns></returns>
        public List<ExcepOrder> SearchRepairForCondition(ExcepOrder repBean, int pageIndex, int pageCount)
        {
            List<ExcepOrder> resList = new List<ExcepOrder>();
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.ExcepOrder.AsQueryable();
                if (repBean != null)
                {
                    if (repBean.ProdNumber != null && repBean.ProdNumber.Trim().Length > 0)
                    {
                        query = query.Where(r => r.ProdNumber.Contains(repBean.ProdNumber.Trim()));
                    }
                }
            }
            return resList;
        }


        /// <summary>
        /// 根据站点查询该站点所有的维修原因
        /// </summary>
        /// <param name="siteID"></param>
        /// <returns></returns>
        public List<RepairReason> SearchRepairReasonForSite(int siteID)
        {
            List<RepairReason> resList = new List<RepairReason>();
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.RepairReason.Where(r => r.SiteID == siteID);
                if (query != null && query.Count() > 0)
                {
                    resList.AddRange(query);
                }
            }
            return resList;
        }


        public int SaveRepairReason(RepairReason tmpBean)
        {
            if (tmpBean != null)
            {
                DateTime tmpDay = this.GetCurrDateTime();
                using (MesDB ctx = new MesDB())
                {
                    if (tmpBean.ID <= 0)
                    {
                        var query = ctx.RepairReason.Where(r => r.SiteID == tmpBean.SiteID && r.Reason == tmpBean.Reason);
                        if (query != null && query.Count() > 0)
                        {
                            throw new Exception("维修原因已经存在，不需再新增！");
                        }
                        else
                        {
                            tmpBean.CreateUser = MainFrm.LoginUser.user_name;
                            tmpBean.CreateDate = tmpDay;
                            ctx.RepairReason.Add(tmpBean);
                        }
                    }
                    else
                    {
                        ctx.RepairReason.Attach(tmpBean);
                        ctx.Entry(tmpBean).State = System.Data.Entity.EntityState.Modified;
                    }
                    return ctx.SaveChanges();
                }
            }
            else
            {
                throw new Exception("没有任何可以保存的资料！");
            }
        }
    }
}
